package org.ezplatform.office.questionnaire.web.rest;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.cloud.api.system.role.RoleApiService;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.component.permission.service.CmpPermissionService;
import org.ezplatform.component.permission.utils.CmpPermissionConstant;
import org.ezplatform.core.annotation.AppLog;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.exception.ValidationException;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.questionnaire.entity.QuestionnaireSet;
import org.ezplatform.office.questionnaire.service.QuestionnaireService;
import org.ezplatform.office.questionnaire.service.QuestionnaireSetService;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping(value = "/api/w/questionnaire/set")
public class QuestionnaireSetWebApiController extends BaseController<QuestionnaireSet, String>{
	
	private final static Logger LOGGER = LoggerFactory.getLogger(QuestionnaireSetWebApiController.class);
	
	@Autowired
	private QuestionnaireSetService questionnaireSetService;
	
	@Autowired
	private QuestionnaireService questionnaireService;
	
	@Autowired
	private PopUserScopeUtilService popUserUtilService;
	
	@Autowired
	private RoleApiService roleApiService;
	
	@Autowired
	private LogService logService;
	
    @Autowired
   	private CmpPermissionService cmpPermissionService;
	
	@Override
	protected BaseService<QuestionnaireSet, String> getEntityService() {
		return questionnaireSetService;
	}
	
	  /**
     * 初始化数据
     * 
     * @param request
     * @param model
     * @param id
     */
    @ModelAttribute
    public void prepareModel(HttpServletRequest request, Model model,
            @RequestParam(value = "id", required = false) String id) {
        super.initPrepareModel(request, model, id);
    }
    
	/**
	 * 获取列表（翻页）数据
	 * 
	 * @param request
	 * @return json
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@RequiresPermissions("stdQuestionnaire:set:03")
	@ResponseBody
	public Page<Map> findByPage(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String corpId = WebUtils.getCurrentUser().getCorpId();
		Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> propertyFilter = PropertyFilter.buildFiltersFromHttpRequest(QuestionnaireSet.class,
				request);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		String sql = "SELECT t.createdBy id, t.id as dataId, t.createdDate, t.set_type, t.set_name, t.set_scope, t.status, t.description, t.sum_topic_num FROM oa_questionnaire_set t WHERE t.corp_id = :corpId ";
		paramMap.put("corpId", corpId);
		// 不是管理员，只能看自己创建的题库
		List<Map<String, Object>> roleList = roleApiService.getRolesByUserId(user.getUserId(), corpId,
				user.getJwtToken());
		boolean result = false;
		if (!roleList.isEmpty()) {
			String roleCode = "";
			for (Map<String, Object> map : roleList) {
				roleCode = StringUtils.null2String(map.get("roleCode"));
				if ("appAdminRole".equals(roleCode)) {
					result = true;
					break;
				}
			}
		}else if("admin".equals(user.getUserName())) {
			result = true;
		}
		if (!result) {
			sql += " and t.createdBy = :createdBy ";
			paramMap.put("createdBy", user.getUserId());
		}
		// 题库类型
		String setType = request.getParameter("setType");
		if (StringUtils.isNotBlank(setType)) {
			sql += " and t.set_type = :setType ";
			paramMap.put("setType", setType);
		}
		// 状态
		String status = request.getParameter("status");
		if (StringUtils.isNotBlank(status)) {
			sql += " and t.status = :status ";
			paramMap.put("status", status);
		}
		// 创建时间开始
		String startTime = request.getParameter("startTime");
		if (StringUtils.isNotBlank(startTime)) {
			sql += " and t.createdDate >= fn_str_to_date(:startTime, 'yyyy-MM-dd HH:mm:ss')";
			paramMap.put("startTime", startTime + " 00:00:00");
		}
		// 截止时间结束
		String endTime = request.getParameter("endTime");
		if (StringUtils.isNotBlank(endTime)) {
			sql += " and t.createdDate <= fn_str_to_date(:endTime, 'yyyy-MM-dd HH:mm:ss')";
			paramMap.put("endTime", endTime + " 23:59:59");
		}
		sql = PropertyFilter.getSqlByFilterAndPageable("t", sql, "t.createdDate desc", propertyFilter, pageable);
		Page<Map> page = questionnaireSetService.findByPageNativeSQL(pageable, sql, paramMap);
		Map<String, String> permissionInfoMap = new HashMap<String, String>();
		// map格式：key-权限编码，value-操作标识
		permissionInfoMap.put("stdQuestionnaire:set:02", CmpPermissionConstant.PERMISSION_NAME_CAN_EDIT);
		permissionInfoMap.put("stdQuestionnaire:set:04", CmpPermissionConstant.PERMISSION_NAME_CAN_DELETE);
		cmpPermissionService.processBaseListByDataScope(page.getContent(), user, permissionInfoMap, "user");
		for(Map<String,Object> ques:page.getContent()) {
			ques.put("id", ques.get("dataId"));
		}
		return page;
	}
    
    /**
     * 保存题库
     * @param entity
     * @param model
     * @return
     * @throws ParseException 
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult save(@ModelAttribute("entity") QuestionnaireSet entity, HttpServletRequest request) throws ParseException {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	String id = entity.getId();
    	String oldName = "";
    	if(StringUtils.isNotBlank(id)) {
    		QuestionnaireSet questionnaireSet = this.questionnaireSetService.findOne(id);
    		oldName = questionnaireSet.getSetName();
    	}
    	Map<String,Object> msg=new HashMap<String,Object>(1);
    	boolean flag = questionnaireSetService.checkName(entity.getId(), entity.getSetName(), corpId);
    	if(flag){
    		msg.put("i18NCode","oa.que.inputnameexist");
    		return OperationResult.buildFailureResult("您输入的题库名称已存在",msg);
    	}
    	boolean checkName = entity.getSetName().contains("<script>");
    	if(checkName) {
    		return OperationResult.buildFailureResult("非法参数，禁止输入");
    	}
    	if(StringUtils.isNotEmpty(entity.getDescription())) {
    		boolean checkDescription = entity.getDescription().contains("<script>");
    		if(checkDescription) {
    			return OperationResult.buildFailureResult("非法参数，禁止输入");
    		}
    	}
    	String jsonStrSetScope = StringUtils.null2String(request.getParameter("jsonStrSetScope"));
    	String setScope = entity.getSetScope();
    	if(StringUtils.isNotBlank(jsonStrSetScope)){
    		if(StringUtils.isBlank(StringUtils.null2String(setScope))){
    			setScope = UuidUtils.UUID();
    			entity.setSetScope(setScope);
    		}
    		this.popUserUtilService.saveScopeData("oa_questionnaire_scope", setScope, jsonStrSetScope, "oa_questionnaire_set","set_scope");
    	}else{
    		if(setScope!=null) {
    			this.popUserUtilService.delScopeMethod("oa_questionnaire_scope",setScope,"oa_questionnaire_set","set_scope");
    		}
    		entity.setSetScope(null);
    	}
    	OperationResult result = super.editSave(entity);
		if("0".equals(result.getCode())) {
			//记录日志
	  		if(StringUtils.isNotEmpty(id)) {
	  		    // 日志启用标记
		    	boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:set:02", TOKEN);
		    	if (optLogFlag) {
		    		this.logService.saveModuleLog("questionnaireLog:set:02", oldName, "");
		    	}
	  		} else {
	  		    // 日志启用标记
		    	boolean optLogFlag = this.logService.checkOptLog(corpId, "questionnaireLog:set:01", TOKEN);
		    	if (optLogFlag) {
		    		this.logService.saveModuleLog("questionnaireLog:set:01", entity.getSetName(), "");
		    	}
	  		} 
		}
		msg.put("i18NCode","oa.que.savesuccess");
    	return OperationResult.buildSuccessResult("保存成功",msg);
    }
    
	/**
	 * 检查实体是否存在
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/entityIsExist", method = RequestMethod.POST)
	@ResponseBody
	public OperationResult entityIsExist(String id) {
		QuestionnaireSet entity = this.questionnaireSetService.findOne(id);
		if (entity == null) {
			return OperationResult.buildSuccessResult("notExist");
		} else {
			return OperationResult.buildSuccessResult("exist");
		}
	}
	
	/**
     * 编辑/新建
     * @param request
     * @return json
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult edit(HttpServletRequest request,@RequestParam("id") String id) {
    	Map<String, Object> map = new HashMap<>();
    	if(StringUtils.isBlank(id)) {
    		return OperationResult.buildSuccessResult(map);
    	}
    	Map<String,Object> entityMap = questionnaireSetService.getQuesSetInfoById(id);
    	map.put("entity", entityMap);
    	String setScope =popUserUtilService.getScopeTypeValue("oa_questionnaire_scope","oa_questionnaire_set", "set_scope",StringUtils.null2String(entityMap.get("set_scope")));
    	map.put("setScope", setScope);
		return OperationResult.buildSuccessResult(map);
    }
    
    /**
     * 查看
     * @param request
     * @return json
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult view(@RequestParam("id") String id, HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	Map<String, Object> map = new HashMap<String, Object>();
    	Map<String,Object> cmap = new HashMap<String, Object>();
		Map<String,Object> entityMap = questionnaireSetService.getQuesSetInfoById(id);
    	map.put("entity", entityMap);
    	String setScope = questionnaireService.getscopeName("oa_questionnaire_set", StringUtils.null2String(entityMap.get("setScope")), "set_scope");
    	cmap.put("setScope", setScope);
    	map.put("views", cmap);
    	// 日志启用标记
    	boolean optLogFlag = this.logService.checkOptLog(user.getCorpId(), "questionnaireLog:set:03", TOKEN);
    	if (optLogFlag) {
    		//记录日志
            this.logService.saveModuleLog("questionnaireLog:set:03", (String)entityMap.get("setName"), "");
    	}
    	return OperationResult.buildSuccessResult(map);
    }
    
    /**
	 * 逻辑删除
	 * @param entity
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	@AppLog
	public OperationResult delete(HttpServletRequest request,Model model, @RequestParam("ids") String... ids) {
		WebUser user = WebUtils.getCurrentUser();
		List<QuestionnaireSet> questionnaireSetList = questionnaireSetService.findAll(ids);
		OperationResult result = super.delete(ids);
		if("0".equals(result.getCode())) {
			boolean optLogFlag = this.logService.checkOptLog(user.getCorpId(), "questionnaireLog:set:04", TOKEN);
	    	//记录日志
	    	if(optLogFlag && CollectionUtils.isNotEmpty(questionnaireSetList)) {
	    		List<Map<String, String>> operateDataList = new ArrayList<>();
	    		for(QuestionnaireSet quSet : questionnaireSetList) {
	    			Map<String, String> operateDataMap = new HashMap<>();
	    			// 操作数据
	    			operateDataMap.put("operateData", quSet.getSetName());
	    			// 操作明细
	    			operateDataMap.put("operateDetails", "");
	    			// 请求Id
	    			operateDataMap.put("requestId", null);
	    			operateDataList.add(operateDataMap);
	    		}
	    		// 记录批量日志
	    		this.logService.batchSaveModuleLog("questionnaireLog:set:04", operateDataList, request);
	    	}
		}
		return result;
	}
	
	/**
	 * 
	 * @Title getQuSetTreeData
	 * @Description: 获取题库树数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getQuSetTreeData", method = RequestMethod.GET)
	@ResponseBody
	public OperationResult getQuSetTreeData(HttpServletRequest request) {
		WebUser user = WebUtils.getCurrentUser();
		String setType = request.getParameter("setType");
		String setName = request.getParameter("searchTreeData");
		String treeData = this.questionnaireSetService.getQuSetTreeData(user.getCorpId(), setType, setName,
				user.getUserId(), user.getJwtToken());
		return OperationResult.buildSuccessResult("获取题库树数据成功", treeData);
	}
	
	 /**
     * 获取题库标题
     * @param request
     * @return 
     */
    @RequestMapping(value = "/setName", method = RequestMethod.GET)
    @ResponseBody
    public OperationResult titleEdit(@RequestParam("id") String id) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	QuestionnaireSet qs = this.questionnaireSetService.findOne(StringUtils.null2String(id));
    	map.put("entity", qs);
    	return OperationResult.buildSuccessResult(map);
    }
    
	 /**
     *设置题库标题
     * @param request
     * @return 
     */
    @RequestMapping(value = "/editSetName", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult setNameEdit(@RequestParam("id") String id,@RequestParam("setName") String setName) {
    	
    	 if(!ValidateUtils.validateComm(setName)) {
    		 throw new ValidationException("非法参数");
    	 }
    	Map<String, Object> map = new HashMap<String, Object>();
    	QuestionnaireSet qs = this.questionnaireSetService.findOne(StringUtils.null2String(id));
    	if(qs!=null) {
    		qs.setSetName(setName);
    		return OperationResult.buildSuccessResult(this.questionnaireSetService.save(qs));
    	}
    	return OperationResult.buildFailureResult("保存题库标题失败");
    }
    
}